import { reactive } from "vue";
import type { FormRules } from "element-plus";
import { isPhone } from "@pureadmin/utils";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";

/** 自定义表单规则校验 */
// 添加一个变量来存储表单的原始名称
let _originalFormName = "";
let originalFormId = 0;
// 导出一个函数来设置原始名称
export function setOriginalFormName(name: string) {
  _originalFormName = name;
}
export function setOriginalFormId(id: number) {
  originalFormId = id;
}
export const formRules = reactive(<FormRules>{
  no: [
    { required: true, message: "用户号为必填项", trigger: "blur" },
    {
      validator: async (rule, value, callback) => {
        if (!value) {
          callback();
          return;
        }
        // 如果原始用户号存在且与当前值相同，则不进行唯一性验证
        if (originalFormId && value === originalFormId) {
          callback();
          return;
        }
        console.log(originalFormId);

        try {
          // 发送请求检查用户号是否存在
          const res = await http.get(
            changeHttpLink("/api/User/check-no-unique"),
            {
              params: {
                userNo: value,
                excludeId: originalFormId ? originalFormId : undefined
              }
            }
          );
          // 添加类型断言以解决TypeScript类型检查问题
          const typedRes = res as {
            Success: boolean;
            Data?: boolean;
          };
          if (typedRes.Success && !typedRes.Data) {
            callback(new Error("用户号已存在"));
          } else {
            callback();
          }
        } catch (error) {
          console.error(error);
          callback(new Error("验证用户号失败，请重试"));
        }
      },
      trigger: "blur"
    }
  ],
  name: [{ required: true, message: "用户名为必填项", trigger: "blur" }],
  zoneId: [{ required: true, message: "区域为必填项", trigger: "change" }],
  type: [{ required: true, message: "类型为必填项", trigger: "change" }],
  categorizeId: [
    { required: true, message: "分类为必填项", trigger: "change" }
  ],
  power: [{ required: true, message: "权限为必填项", trigger: "blur" }],
  disabled: [{ required: true, message: "状态为必填项", trigger: "change" }],
  expire: [{ required: true, message: "过期时间为必填项", trigger: "change" }],
  username: [{ required: true, message: "用户名为必填项", trigger: "blur" }],
  phone: [
    {
      validator: (rule, value, callback) => {
        if (value === "") {
          callback();
        } else if (!isPhone(value)) {
          callback(new Error("请输入正确的手机号码格式"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
});
